import React, { memo, useEffect, useState } from 'react'
import { connect } from 'react-redux'
import UserLove from '../../components/shoppingCart/userLove/UserLove'
import {reqClassifyListData} from '@/api'
import shoppingCartImg from '@/assets/images/shoppingCart.png'
import ShoppingCartItem from '@/components/shoppingCart/shoppingCartItem/ShoppingCartItem'
import { Page,Footer } from './style'
import  * as actionTypes from './store/actionCreators'
import Toast from '@/baseUI/Toast'

function ShoppingCart(props) {
    const {shoppingCartCount,setShoppingCartCount}=props

    const [goodsList,setGoodsList]=useState([])
    const [shoppingCartList,setShoppingCartList]=useState([])
    const [checkedCount,setCheckedCount]=useState(0)
    const [totalCost,setTotalCost]=useState(0)
    const [checkedAll,setCheckedAll]=useState(false)
    const [isEdit,setIsEdit]=useState(false)

    const changeAll=()=>{
        let sumCost=0;
        const newCartList=[...shoppingCartList].map((item)=>{
            sumCost+=item.price*item.goodsAttributeChecked.count
            return {
                ...item,
                checked:!checkedAll
            }
        })
        if(!checkedAll){
            setCheckedCount(newCartList.length)
            setTotalCost(sumCost)
        }
        else{
            setCheckedCount(0)
            setTotalCost(0)
        }
        setCheckedAll(!checkedAll)
        setShoppingCartList(newCartList)
        console.log(shoppingCartList)
    }

    const changeOne=(id)=>{
        const index=shoppingCartList.findIndex((item)=>{
            return item.id==id
        })
        const newList=[...shoppingCartList]
        const targetItem=newList[index]
        if(targetItem.checked){
            setTotalCost(((totalCost)*10-(targetItem.price)*10)/10)  // 防止js小数算错
            setCheckedCount(checkedCount-1)
            setCheckedAll(false)
        }
        else{
            setTotalCost(((totalCost)*10+(targetItem.price)*10)/10)
            setCheckedCount(checkedCount+1)
            if(checkedCount+1>=shoppingCartList.length){
                setCheckedAll(true)
            }
        }
        newList[index]={...targetItem,checked:!targetItem.checked}
        setShoppingCartList(newList)
    }

    const deleteGoods=()=>{
        const newList=[...shoppingCartList].filter((item)=>{
            return !item.checked
        })
        setShoppingCartList(newList)
        setTotalCost(0)
        setCheckedCount(0)
    }

    const buyGoods=()=>{
        Toast("购买成功")
        deleteGoods()
        // reqbuy()
    }

    useEffect(()=>{
        reqClassifyListData('猜你喜欢',1)
            .then(res=>{
                setGoodsList(res.data.data.classifylistdata)
            })
        setShoppingCartList(JSON.parse(localStorage.getItem('shoppingCartList'))||[])
        // console.log(JSON.parse(localStorage.getItem('shoppingCartList')))
        
        const storageCheckedCount=JSON.parse(localStorage.getItem('checkedCount'))
        const storageTotalCost=JSON.parse(localStorage.getItem('totalCost'))
        if(setTotalCost) setTotalCost(storageTotalCost)
        if(storageCheckedCount) setCheckedCount(storageCheckedCount)
    },[])

    useEffect(()=>{
        setShoppingCartCount(shoppingCartList.length)
        return ()=>{
            localStorage.setItem('shoppingCartList',JSON.stringify(shoppingCartList))
            localStorage.setItem('checkedCount',JSON.stringify(checkedCount))
            localStorage.setItem('totalCost',JSON.stringify(totalCost))
        }
    },[shoppingCartList])

    return (
        <Page>
            <div className="header">
                <div>购物车</div> 
                <button onClick={()=>setIsEdit(!isEdit)}>{!isEdit?"编辑":"完成"}</button>
            </div>
            {
                !shoppingCartCount?
                <div className='nocount'>
                    <img src={shoppingCartImg} alt="" />
                    <div>去添加点什么吧</div>
                </div>:
                <div>
                    {
                        shoppingCartList.map((item,index)=>{
                            return (
                                <ShoppingCartItem shoppingCartItem={item} key={index+'cartItem'} changeOne={changeOne} />
                            )
                        })
                        
                    }
                </div>
            }
            <UserLove goodsList={goodsList} />
            {
                shoppingCartCount&&<Footer>
                <div className='choose'>
                    <input type="checkbox" id='allchoose' checked={checkedAll} onChange={changeAll} />
                    <label htmlFor='allchoose'>已选({checkedCount})</label>
                </div>
                {
                    isEdit?
                    <div className="delete">
                        <button className={checkedCount>0?'enable':''} onClick={deleteGoods} disabled={checkedCount>0?false:true} >删除</button>
                    </div>:
                    <div className='buy'>
                        <span>合计:￥{totalCost}</span>
                        <button className={checkedCount>0?'enable':''} onClick={buyGoods} disabled={checkedCount>0?false:true}>下单</button>
                    </div>
                }
            </Footer>
            } 
        </Page>
    )
}

const mapStateToPorps=(state)=>{
    return {
        shoppingCartCount:state.shoppingCart.shoppingCartCount,
    }
}

const mapStateToDispatch=(dispatch)=>{
    return {
        setShoppingCartCount(count){
            dispatch(actionTypes.setShoppingCartCount(count))
        }
    }
}

export default connect(mapStateToPorps,mapStateToDispatch)(memo(ShoppingCart))
